package cn.itcast.tanhua.mytanhuaserver.interceptor;


import cn.hutool.core.util.StrUtil;
import cn.itcast.tanhua.constant.RedisKeyConstant;
import cn.itcast.tanhua.mytanhuaserver.mapper.UserMapper;
import cn.itcast.tanhua.mytanhuaserver.service.UserService;
import cn.itcast.tanhua.pojo.User;
import cn.itcast.tanhua.utils.NoAuthorization;
import cn.itcast.tanhua.utils.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Component
public class UserTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    private static String USER_STATUS = "USER_STATUS_";

    private User user1;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //校验handler是否是HandlerMethod
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        //判断是否包含@NoAuthorization注解，如果包含，直接放行
        if (((HandlerMethod) handler).hasMethodAnnotation(NoAuthorization.class)) {
            return true;
        }


        //从请求头中获取token
        String token = request.getHeader("Authorization");
        //Map<String,String> map = new HashMap<>();
        if (StrUtil.isNotEmpty(token)){
            //查redis
            User user = userService.queryUserByToken(token);
            String redisKey = RedisKeyConstant.TANHUA_USER_MOBILE_USERID + user.getId();
            //查mysql
            user1 = userService.queryUserByUserId(user.getId());
            //判断redis中的状态与MySQL中的状态是否一致
            if (!StrUtil.equals(user.getStatus(),user1.getStatus())){
                //获取redis中status的值
                String s = redisTemplate.opsForValue().get(redisKey);
                System.out.println(s);
                //不一致
                user.setStatus(user1.getStatus());
                //删除
                redisTemplate.delete(redisKey);
                redisTemplate.opsForValue().set(redisKey,user.getStatus());
            }
            //判断user是否为null
            if (user != null){
                //获取用户状态
                String status = user.getStatus();
                //判断状态是否为白名单"0"
                if (StrUtil.equals("0",status)){
                    UserThreadLocal.set(user);
                    return true;
                }
                if (StrUtil.equals("1",status)){
                    //response.setStatus(401); //无权限
                    response.sendError(200,"用户被禁用");
                    return false;
                }
            }
        }
        //token无效，响应状态为401
        response.setStatus(401); //无权限
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //从ThreadLocal中移除User对象
        UserThreadLocal.remove();
    }
}